Java复制文件并且替换源文件内容

首先,创建一个类 要求输入文件夹地址,目标文件地址,要更改的K_V集合,还有编码方式



        //全局变量Map  和需要用字符流读取的文件(可以自己适当改变问价后缀)

        private static Map<String, String> map = new HashMap<>();

private static String[] replaceContentFileExtName = new String[] { ".java", ".properties", ".xml" };



/**

* @param fileName

*            文件名

* @param map

*            输入k_v集合 subProjectName 项目名 webProjectName 项目名 rpcProjectName 项目名

*            packageName 包名 javaCompileLevel java编译版本

* @param dirName

*            需要复制的文件夹的内容

* @param codeRule

*            编码格式

* @throws IOException

*/

public static void getProductBak(String fileName, String targetDirectoryName, Map<String, String> map,

String codeRule) throws IOException {




if (fileName == null || "".equals(fileName)) {        

System.out.println("请输入源文件夹名");        //判断文件是否为空

return;


}

String sourceCurrentPath = "";

if (fileName.contains(File.separator)) {

sourceCurrentPath = fileName;       

} else {

sourceCurrentPath = CopyFileDemo.getDesktopPath() + fileName + File.separator;

}                                    //获取桌面地址   拼接路径

File sourceModel = new File(sourceCurrentPath);     //创建以输入路径名的新文件

if (sourceModel == null) {

return;

}

String projectPath = "";

if (targetDirectoryName != null && targetDirectoryName.contains(map.get("projectName"))) {

projectPath = targetDirectoryName;

} else {

projectPath = CopyFileDemo.getDesktopPath() + map.get("projectName") + File.separator;

new File(projectPath).mkdir();  

}    //判断名字是否全路径    

File[] sourceFiles = sourceModel.listFiles();

if (sourceFiles == null || sourceFiles.length == 0) {

return;

}



for (File currentFile : sourceFiles) {

String currentFilePath = currentFile.getPath();

String currentFileName = currentFile.getName();

currentFileName = replaceVailable(currentFileName, map); //替换文件名字中的变量

boolean isFile = currentFile.isFile();

// is File,copy File

if (isFile) {       //判断是否是文件

// ignore DS_Store

if (currentFileName.contains("DS_Store")) {   //Mac下隐藏文件夹去掉

continue;

}

// create new file

String newTargetFilePath = projectPath + currentFileName + File.separator;

new File(newTargetFilePath).createNewFile();

// copy file

// byte (java properties xml) or chars

if (getFileIsByte(currentFileName)) {

InputStream is = new FileInputStream(currentFilePath);

OutputStream os = new FileOutputStream(newTargetFilePath);

byte[] buff = new byte[1024];

int length = -1;

while ((length = is.read(buff)) != -1) {

os.write(buff, 0, length);

}

os.flush();

os.close();

is.close();

// byte

} else {    

BufferedReader reader = new BufferedReader(new FileReader(currentFilePath));

BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(new FileOutputStream(newTargetFilePath), Charset.forName(codeRule)));

String readStr = "";

while ((readStr = reader.readLine()) != null) {

readStr = replaceVailable(readStr, map);

writer.write(readStr + "\n");

}

reader.close();

writer.flush();

writer.close();

}

} else {    //判断是否是文件夹


// is Directory,mkdir


if (currentFileName.startsWith(".")) {


System.out.println(currentFileName);


currentFileName = directoryNameHandle(currentFileName);


currentFileName = currentFileName.substring(1, currentFileName.length());

System.out.println(projectPath + "." + currentFileName + File.separator);


new File(projectPath + "." + currentFileName + File.separator).mkdirs();


}


currentFileName = directoryNameHandle(currentFileName);


new File(projectPath + currentFileName + File.separator).mkdirs();


getProductBak(currentFilePath, projectPath + currentFileName + File.separator, map, codeRule);


}


}



//包名分级创建文件夹

public static String directoryNameHandle(String name) {


if (name != null && !"".equals(name) && !name.contains(".") && !name.startsWith("\\.")

&& name.contains("package")) {


return replaceVailable(name, map);


}


name = replaceVailable(name, map);


String[] paths = name.split("\\.");


String result = "";


for (String path : paths) {


result = result + path + File.separator;


}


return result;


}


// desktop path

public static String getDesktopPath() {

FileSystemView fsv = FileSystemView.getFileSystemView();

File com = fsv.getHomeDirectory();

return com.getPath() + File.separator;

}


//要复制的文件夹变量用$$括起来  以下方法替换变量

public static String replaceVailable(String sourceStr, Map<String, String> model) {

for (String key : model.keySet()) {

if (sourceStr.contains("$" + key + "$")) {

sourceStr = sourceStr.replace("$" + key + "$", model.get(key));

}

}

return sourceStr;

}



//判断用字节文件读取文件  还是字符流读取

public static boolean getFileIsByte(String fileName) {

if (fileName == null || "".equals(fileName)) {

return true;

}

for (String extName : replaceContentFileExtName) {

if (fileName.endsWith(extName)) {

return false;

}

}

return true;

}



Java中,复制文件文件夹可以通过`java.io.File`和`java.nio.file.Files`类提供的方法来实现。这里是一个简单的示例: ```java import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileCopyExample { public static void main(String[] args) { // 原始文件路径 String sourceFilePath = "path/to/source/file.txt"; // 目标文件夹路径 String targetDirectoryPath = "path/to/destination/folder"; try { // 获取源文件对象 File sourceFile = new File(sourceFilePath); // 创建目标目录(如果不存在) if (!new File(targetDirectoryPath).exists() && !new File(targetDirectoryPath).mkdirs()) { System.out.println("Failed to create the target directory."); return; } // 构建完整的目标文件路径 String targetFilePath = Paths.get(targetDirectoryPath, sourceFile.getName()).toString(); // 复制文件 Path destination = Paths.get(targetFilePath); Files.copy(sourceFile.toPath(), destination, StandardCopyOption.REPLACE_EXISTING); // 如果目标文件已存在,会覆盖 System.out.println("File copied successfully from " + sourceFilePath + " to " + targetFilePath); } catch (Exception e) { System.err.println("An error occurred while copying the file: " + e.getMessage()); e.printStackTrace(); } } } ``` 在这个代码片段中,我们首先创建`File`对象表示源文件,然后检查并创建目标文件夹(如果不存在)。接着,我们将源文件复制到目标文件夹中的相同名称的新文件,如果目标文件已经存在,我们会用`StandardCopyOption.REPLACE_EXISTING`选项替换掉。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值